<template>
    <a-drawer
        v-if="visible"
        :append-to-body="true"
        :width="540"
        :visible="visible"
        :closable="false"
        @cancel="closeDrawer()"
        @ok="saveTrigger()"
        ok-text="保存">
        <template #title>
            <EditableText :value="flowNodeConfig.name" @change="(v) => (flowNodeConfig.name = v)" />
        </template>
        <div>
            <p style="background-color: #ff0073;">
                触发器支持模板变量替换语法 ${变量名}， 变量名支持所有的<br/>
                【表单字段ID】及【扩展变量】<br/>
                扩展变量如下：[formName 审批表单名] [instanceId 审批实例ID]<br/>
                [ownerId 发起人ID] [ownerName 发起人名]<br/>
                [ownerDeptId 发起人部门ID] [ownerDeptName 发起人部门名]<br/>
            </p>
        </div>
        <div style="margin-bottom: 20px">
            <p class="item-desc">选择触发的动作</p>
            <div class="main-content">
                <a-radio-group type="button" class="radio-group" v-model="flowNodeConfig.TriggerConfig.type" >
                    <a-radio value="WEBHOOK">发送网络请求</a-radio>
                    <a-radio value="EMAIL">发送邮件</a-radio>
                </a-radio-group>
            </div>
        </div>
        <div v-if="flowNodeConfig.TriggerConfig.type === 'WEBHOOK'">
            <div style="margin-bottom: 20px">
                <p class="item-desc">请求地址</p>
                <a-select slot="append" v-model="flowNodeConfig.TriggerConfig.http.method" :style="{width:'120px'}">
<!--                    <a-option value="GET">GET</a-option>-->
<!--                    <a-option value="POST">POST</a-option>-->
<!--                    <a-option value="PUT">PUT</a-option>-->
<!--                    <a-option value="DELETE">DELETE</a-option>-->
					<a-option value="GTJA_OA_DOCUMENT_PUSH">OA接口</a-option>
					<a-option value="GTJA_OA_DOCUMENT_AUDIT">OA审核</a-option>
					<a-option value="GTJA_NC_DOCUMENT_PUSH">财务接口</a-option>
					<a-option value="GTJA_NC_DOCUMENT_AUDIT">财务审核</a-option>
					<a-option value="GTJA_NC_DOCUMENT_IN_AUDIT">调入审核</a-option>
					<a-option value="GTJA_NC_DOCUMENT_OUT_AUDIT">调出审核</a-option>
                </a-select>
                <a-input :style="{width:'70%'}" v-model="flowNodeConfig.TriggerConfig.http.url" placeholder="请输入URL地址" allow-clear />
            </div>
            <div style="margin-bottom: 20px">
                <div style="margin-bottom: 20px">
                    <span>Header请求头
                        <a-button type="text" @click="addItem(flowNodeConfig.TriggerConfig.http.headers)"><span> + 添加</span></a-button>
                    </span>
                </div>
                <div v-for="(header, index) in flowNodeConfig.TriggerConfig.http.headers || []" :key="header.name">
                    -<a-input :style="{width:'20%'}" v-model="header.name" placeholder="参数名" allow-clear />
                    <a-radio-group default-value=true  type="button" class="radio-group" v-model="header.isField">
                        <a-radio :value=true>表单</a-radio>
                        <a-radio :value=false>固定</a-radio>
                    </a-radio-group>
                    <template v-if="header.isField">
                        <a-select style="width: 30%;" v-if="header.isField" v-model="header.value" placeholder="请选择表单字段" @change="onConditionChange($event, header)">
                            <a-option v-for="opt in conditionOptions" :value="opt.name">{{ opt.label }}</a-option>
                        </a-select>
                    </template>
                    <template v-else>
                        <a-input allow-clear placeholder="请设置字段值" size="small" v-model="header.value" style="width: 30%;"/>
                    </template>
                    <icon-delete class="branch-delete-icon" @click="delItem(flowNodeConfig.TriggerConfig.http.headers, index)" />
                </div>
            </div>
            <div style="margin-bottom: 20px">
                <div style="margin-bottom: 20px">
                    <span>Header请求参数
                        <a-button type="text" @click="addItem(flowNodeConfig.TriggerConfig.http.params)"><span> + 添加</span></a-button>
                    </span>
                    <span>参数类型 - </span>
                    <a-radio-group type="button" class="radio-group" v-model="flowNodeConfig.TriggerConfig.http.contentType">
                        <a-radio value="JSON">json</a-radio>
                        <a-radio value="FORM">form</a-radio>
                    </a-radio-group>
                </div>
                <div v-for="(param, index) in flowNodeConfig.TriggerConfig.http.params || []" :key="param.name">
                    -<a-input :style="{width:'20%'}" v-model="param.name" placeholder="参数名" allow-clear />
                    <a-radio-group type="button" class="radio-group" v-model="param.isField">
                        <a-radio :value=true>表单</a-radio>
                        <a-radio :value=false>固定</a-radio>
                    </a-radio-group>
                    <!-- <a-select style="width: 20%;" v-if="param.isField" v-model="param.value" placeholder="请选择表单字段">
                        <a-option v-for="form in forms" :key="form.id" :value="form.id" :label="form.title"></a-option>
                    </a-select> -->
                    <template v-if="param.isField">
                        <a-select style="width: 30%;" v-model="param.value" placeholder="请选择表单字段" @change="onConditionChange($event, param)">
                            <a-option v-for="opt in conditionOptions" :value="opt.name">{{ opt.label }}</a-option>
                        </a-select>
                    </template>
                    <template v-else>
                        <a-input allow-clear placeholder="请设置字段值" size="small" v-model="param.value" style="width: 30%;"/>
                    </template>
                    <icon-delete class="branch-delete-icon" @click="delItem(flowNodeConfig.TriggerConfig.http.params, index)" />
                </div>
            </div>
            <div style="margin-bottom: 20px">
                <div style="margin-bottom: 20px">
                    <span>请求结果处理</span>
                    <span style="margin-left: 20px">自定义脚本: </span>
                    <a-switch v-model="flowNodeConfig.TriggerConfig.http.handlerByScript">
                        <template #checked>
                            ON
                        </template>
                        <template #unchecked>
                            OFF
                        </template>
                    </a-switch>
                    <template v-if="flowNodeConfig.TriggerConfig.http.handlerByScript">
                        <div style="margin-bottom: 20px">
                            <span class="item-desc" >
                                👉 返回值为 ture 则流程通过，为 false 则流程将被驳回
                                <div>支持函数
                                    <span style="color: dodgerblue">setFormByName(
                                    <span style="color: #939494">'表单字段名', '表单字段值'</span>
                                    )</span>
                                    可改表单数据
                                </div>
                            </span>
                        </div>
                    </template>
                    <template v-else>
                        <span class="item-desc">👉 无论请求结果如何，均通过</span>
                    </template>
                </div>
                <div v-if="flowNodeConfig.TriggerConfig.http.handlerByScript">
                    <div>
                    <span>请求成功😀：</span>
                    <a-textarea type="textarea" default-value="function handlerOk(res) {
  return true;
}" auto-size v-model="flowNodeConfig.TriggerConfig.http.success" allow-clear :rows="3">

                    </a-textarea>
                    </div>
                    <div>
                    <span>请求失败😥：</span>
                    <a-textarea type="textarea" default-value="function handlerFail(res) {
  return true;
}" auto-size v-model="flowNodeConfig.TriggerConfig.http.fail" allow-clear :rows="3"></a-textarea>
                    </div>
                </div>
            </div>
        </div>
        <div v-else-if="flowNodeConfig.TriggerConfig.type === 'EMAIL'" style="margin-bottom: 20px">
            <p class="item-desc">邮件主题</p>
            <div style="margin-bottom: 20px">
                <a-input placeholder="请输入邮件主题" size="medium" v-model="flowNodeConfig.TriggerConfig.email.subject" style="width: 180px;"/>
            </div>
            <p class="item-desc">收件方</p>
            <div style="margin-bottom: 20px">
                <div class="assignee-box">
                    <a-button size="small" @click="onAssigneeClick(flowNodeConfig.TriggerConfig.email)"><icon-plus /></a-button>
                    <span class="assignee-list">
                        <a-tag v-for="userId in flowNodeConfig.TriggerConfig.email.to">{{ getUserById(userId).name }}</a-tag>
                    </span>
                    <OrganChooseBox
                    v-if="showChooseAssignee"
                    v-model:visible="showChooseAssignee"
                    v-model:selected="selectedAssignee.to"
                    :hidden-dept="true"
                    :hidden-role="true" />
                </div>
            </div>
            <p class="item-desc">邮件正文</p>
            <div style="margin-bottom: 20px">
                <a-textarea type="textarea" auto-size v-model="flowNodeConfig.TriggerConfig.email.content" placeholder="邮件内容，支持变量提取表单数据 ${表单字段名} " allow-clear :rows="3"></a-textarea>
            </div>
        </div>
    </a-drawer>
</template>
<script setup>
import { computed, onBeforeMount, onMounted, ref, toRaw, watch } from "vue";
import { useFlowStore, useOrganStore } from "@/store/flowable/index";
import ArrayUtil from "@/components/flowable/flow/common/ArrayUtil";
import Snowflake from "@/components/flowable/flow/common/Snowflake";
import OrganChooseBox from "@/components/flowable/flow/dialog/OrganChooseBox.vue";
import { WIDGET } from "@/components/flowable/flow/common/FlowConstant";
import { ASSIGNEE } from "@/components/flowable/flow/common/FlowConstant";
import ObjectUtil from "@/components/flowable/flow/common/ObjectUtil";
import { names as FunNames } from "@/components/flowable/flow/common/FormExp";
import { IconDelete, IconSwap, IconPlus } from "@arco-design/web-vue/es/icon";
import { Notification } from "@arco-design/web-vue";
import EditableText from "@/components/flowable/common/EditableText.vue";

let flowStore = useFlowStore();
const { getById, roles: allRoles, users: allUsers, getUserById, depts: allDepts } = useOrganStore();
let { showTriggerDrawer, setTriggerConfig , flowDefinition} = flowStore;
let isTriggerDrawerOpened = computed(() => flowStore.isTriggerDrawerOpened);
let triggerConfig0 = computed(() => flowStore.triggerConfig0);
let visible = ref(false); // 是否显示
let _uid = ref(0);
let flowNodeConfig = ref({
});
// 所有的条件选项，该处值是表单编辑器传递过来的
let conditionOptions = ref([]);
let selectedGroupCondition = ref({}); // 当前选中的分组条件
// 收件人选择指定成员
let showChooseAssignee = ref(false);
let selectedAssignee = ref({});
const onAssigneeClick = (item) => {
    selectedAssignee.value = item;
    showChooseAssignee.value = true;
};
watch(triggerConfig0, (val) => {
    flowNodeConfig.value = val.value;
    _uid = val.id;
});
const addItem = (items)=> {
      if (
        items.length > 0 &&
        (items[items.length - 1].name.trim() === "" ||
          items[items.length - 1].value.trim() === "")
      ) {
        setTimeout(() => Notification.error("请完善之前项后在添加"), 1 * 50);
        return;
      }
      items.push({ name: "", value: "", isField: true });
};
const delItem = (items, index) => {
      items.splice(index, 1);
};

// 侧边栏是否打开
watch(
  () => flowStore.isTriggerDrawerOpened,
  (isOpen) => {
    visible.value = isOpen;
    if (isOpen) initCondition();
  }
);

// 侧边栏打开初始化
const initCondition = () => {
  let val = triggerConfig0.value;
  //console.log(val)
  // 初始化分组条件选项
  conditionOptions.value = [{ name: "initiator", label: "发起人", operators: [20, 21] }];
  // 将表单必填项转换为分支条件
	let widgets = [];
	if(flowDefinition.flowWidgets){
		widgets = ObjectUtil.copy(toRaw(flowDefinition.flowWidgets));
	}
  if (widgets && widgets.length > 0) {
    widgets.forEach((widget) => {
      let { type, required, details } = widget;
      // 非明细组件
      if (required) {
        if ([WIDGET.SINGLELINE_TEXT].includes(type)) widget.operators = [14, 15, 10, 11, 12, 13];
        else if ([WIDGET.NUMBER, WIDGET.MONEY, WIDGET.DATE_RANGE].includes(type)) widget.operators = [0, 1, 2, 3, 4, 5];
        else if ([WIDGET.SINGLE_CHOICE].includes(type)) {
          widget.operators = [12, 13];
          widget.options = widget.options.filter((item) => !!item); // 过滤掉为空的选项
        } else if ([WIDGET.MULTI_CHOICE].includes(type)) {
          widget.operators = [20, 21];
          widget.options = widget.options.filter((item) => !!item);
        } else if ([WIDGET.DATE].includes(type)) widget.operators = [12, 13];
        else if ([WIDGET.DEPARTMENT, WIDGET.EMPLOYEE].includes(type)) widget.operators = [20, 21];

        // 加入条件列表
        if (widget.operators) conditionOptions.value.push(widget);
      }

      // 明细组件
      if (type == WIDGET.DETAIL && details && details.length > 0) {
        details.forEach((detail) => {
          let { type: detailType, required: detailRequired } = detail;
          if (detailRequired && [WIDGET.NUMBER, WIDGET.MONEY].includes(detailType)) {
            detail.operators = [0, 1, 2, 3, 4, 5];
            detail.label = detail.label + "（合计）";
            conditionOptions.value.push(detail);
          }
        });
      }
    });
  }
};
// 条件选项切换
const onConditionChange = (optionName, condition) => {
  // 当前选择的条件
  selectedGroupCondition.value = condition;
  let option = ArrayUtil.get(conditionOptions.value, "name", optionName);
  // 清除选中的操作
  condition.operator = null;
  // 清除条件值
  condition.val = null;
  // 设置操作符选项
  if (option) condition.operators = option.operators || [];
};
// 根据组件名称获取组件
const getWidget = (name) => {
  return ArrayUtil.get(conditionOptions.value, "name", name) || {};
};

// 条件组相关操作
const addConditionGroup = () => {
  let { conditionGroups } = flowNodeConfig.value;
  if (!conditionGroups) flowNodeConfig.value.conditionGroups = conditionGroups = [];
  conditionGroups.push({ id: Snowflake.generate(), conditions: [{ id: Snowflake.generate() }] });
};
const rmConditionGroup = (conditionGroup) => {
  ArrayUtil.remove(flowNodeConfig.value.conditionGroups, "id", conditionGroup.id);
};
const addCondition = (conditionGroup) => {
  conditionGroup.conditions.push({ id: Snowflake.generate() });
};
const rmCondition = (conditionGroup, condition) => {
  ArrayUtil.remove(conditionGroup.conditions, "id", condition.id);
};

const saveTrigger = () => {
  setTriggerConfig({
    value: toRaw(flowNodeConfig.value),
    flag: true,
    id: _uid,
  });
  closeDrawer();
};
const closeDrawer = () => {
  showTriggerDrawer(false);
};

onBeforeMount(() => {});
onMounted(() => {});
</script>
<style lang="less">
.branch-delete-icon {
    font-size: 18px;
    cursor: pointer;
  }
.approver-list {
        .approver-wrapper {
          border: 1px solid #e4e5e7;
          border-radius: 6px;
          overflow: hidden;

          + .approver-wrapper {
            margin-top: 6px;
          }

          .header {
            padding: 0 16px;
            background: #f5f6f7;
            height: 36px;
            line-height: 36px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            span {
              color: #1f2329;
              font-weight: 600;
            }

            .arco-icon {
              cursor: pointer;
              &:hover {
                color: #3370ff;
              }
            }
          }

          // .main-content {
          // }

          .sub-content {
            padding: 0 16px 10px;

            .sub-content-top-line {
              border-top: 1px solid #dee0e3;
            }

            p {
              padding-top: 10px;
              color: #1f2329;
              font-size: 14px;
              font-weight: 600;
              margin-bottom: 8px;

              span {
                color: #8f959e;
                font-weight: 400;
                font-size: 13px;
              }
            }

            .arco-form-item {
              margin-bottom: 0;
            }

            .assignee-box {
              display: flex;
              align-items: center;
              justify-content: space-between;

              .assignee-list {
                flex: 1;
                margin-left: 10px;
                display: flex;
                flex-wrap: wrap;
                gap: 4px;

                .arco-tag {
                  height: 28px;
                }
              }
            }
          }

          .radio-group {
            padding: 10px 16px;
            width: 100%;

            .arco-radio {
              margin-right: 2px;
            }
          }
        }
      }
</style>
